#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
#include<unordered_set>
using namespace std;


struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x):val(x), left(nullptr), right(nullptr){}
};

class Solution{
    public:
    
    TreeNode* ans1(TreeNode* root){
        return change(root);
    }

    TreeNode* change(TreeNode* root){

        if(root == nullptr){
            return nullptr;
        }
        TreeNode* left = change(root->left);
        TreeNode* right = change(root->right);
        root->left = right;
        root->right = left;
        return root;
    }

    //递归
    TreeNode* ans2(TreeNode* root){
        if(root == nullptr){
            return nullptr;
        }
    
        TreeNode* temp = root->left;
        root->left = root->right;
        root->right = temp;

        ans2(root->left);
        ans2(root->right);
        return root;

    }

    void frontTraverse(TreeNode* root, vector<int>& val){
        if(root == nullptr){
            return;
        }
        val.push_back(root->val);
        frontTraverse(root->right, val);
        frontTraverse(root->left, val);
    }

    void myfrontTraverse(TreeNode* root, vector<int>& val){
        if(root == nullptr){
            val.push_back(-INT16_MAX);
            return;
        }
        val.push_back(root->val);
        myfrontTraverse(root->left, val);
        myfrontTraverse(root->right, val);
    }


    TreeNode* createTree(vector<int> nums, int index, int len){
        if(nums[index] == '#'){
            return NULL;
        }
        TreeNode* root = new TreeNode(nums[index]);

        if(index * 2 + 1 < len){
            root->left = createTree(nums, index * 2 + 1, len);
        }else{
            root->left = NULL;
        }
        if(index * 2 + 2 < len){
            root->right = createTree(nums, index * 2 + 2, len);
        }else{
            root->right = NULL;
        }
        return root;
    }

    void show(vector<int>& val){
        int len = val.size();
        for(int i = 0; i != len-1; i++){
            cout << val[i] << " " << ends;
        }
        cout << val[len-1] << endl;
        val.clear();
    }

};

void test1(){
    Solution s;

    vector<int> num = {4,2,7,1,3,6,9};
    TreeNode* root = s.createTree(num, 0, num.size());
    vector<int> val;
    s.frontTraverse(root, val);
    s.show(val); val.clear();
    // TreeNode* ret = s.ans1(root);
    TreeNode* ret = s.ans2(root);
    s.frontTraverse(ret, val);
    s.show(val); val.clear();
    
}

void test2(){
    Solution s;

    vector<int> num = {2,1,3};
    TreeNode* root = s.createTree(num, 0, num.size());
    vector<int> val;
    s.frontTraverse(root, val);
    s.show(val); val.clear();
    TreeNode* ret = s.ans1(root);
    s.frontTraverse(ret, val);
    s.show(val); val.clear();
}


int main(void){
    test1();
    test2();

    return 0;
}